package com.lvhx.springboot.springbatch.base;

import com.lvhx.springboot.partitioner.ParametersProvider;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

import java.util.Map;

public class CustomTasklet implements Tasklet {
    private String configKey;
    private TaskletAppl taskletAppl;
    private Map<String, Object> jobParameters;
    private ParametersProvider parametersProvider;
    private ActionExecutor actionExecutor;

    public CustomTasklet(String configKey,
                         TaskletAppl taskletAppl,
                         ActionExecutor actionExecutor,
                         ParametersProvider parametersProvider,
                         Map<String, Object> jobParameters){
        this.taskletAppl = taskletAppl;
        this.configKey = configKey;
        this.actionExecutor = actionExecutor;
        this.parametersProvider = parametersProvider;
        this.jobParameters = jobParameters;
    }

    @Override
    public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
//        final Map<String,Object> jobParameters = chunkContext.getStepContext().getJobParameters();

        Parameters parameters = collectParameters(chunkContext);
        actionExecutor.excute(new ActionCallback() {
            @Override
            public <T> T doAction() {
                taskletAppl.process(parameters);
                return null;
            }
        });
        return null;
    }


    // 查询批量库里配置的批量参数
    private Parameters collectParameters(ChunkContext chunkContext) {
        Parameters parameters = parametersProvider.loadParameters(configKey);

        for (Map.Entry<String, Object> entry : jobParameters.entrySet()) {
            parameters.putData(entry.getKey(), entry.getValue());
        }

        Map<String, Object> jobCtx = chunkContext.getStepContext().getJobExecutionContext();
        if (jobCtx != null) {
            for (Map.Entry<String, Object> entry : jobCtx.entrySet()) {
                parameters.putData(entry.getKey(), entry.getValue());
            }
        }
        return parameters;
    }
}
